package com.weixin.program.servlet;

import com.weixin.program.config.WeixinProperties;
import com.weixin.program.constant.Constants;
import com.weixin.program.delay.DelayQueueTask;
import com.weixin.program.ro.UserData;
import com.weixin.program.service.RecordService;
import com.weixin.program.utils.HttpClientProxy;
import com.weixin.program.utils.TemplateUtil;
import com.weixin.program.utils.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Slf4j
@WebServlet(urlPatterns = "/api/program/v1/wx_contact")
public class WeixinServlet extends HttpServlet {

    @Autowired
    WeixinProperties properties;

    @Autowired
    RecordService recordService;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");

        log.info("获取微信请求参数 : signature={},timestamp={},nonce={},echostr={}", new Object[]{signature, timestamp, nonce, echostr});
        String sha1 = WeixinUtil.getSHA1(new String[]{properties.getToken(), timestamp, nonce});
        if (!signature.equals(sha1)) {
            log.error("signature校验失败，请检查......");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write("signature校验失败......");
        } else {
            if (StringUtils.isNotBlank(echostr)) {
                resp.getWriter().write(echostr);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("UTF-8");
        try {
            // 1、保存数据
            Map map = WeixinUtil.parseXml(req);
            log.info("获取微信请求参数 {}:", map.toString());
            String content = (String) map.get("Content");
            if (Constants.RECORDED.equals(content) || Constants.RECORD_SUCCESS.equals(content)) {
                map.put("Content", Constants.RECORDED);
                recordService.save(map);
                // 2、返回响应
                DelayQueueTask.clearDelayQueue();
                String token = WeixinUtil.getToken(properties.getAppid(), properties.getAppsecret());
                String touserid = properties.getTouserid();
                UserData userData = WeixinUtil.getUserData(touserid, token);
                String noticeMsg = TemplateUtil.buildNoticeDoneMsg(properties.getTouserid(), userData.getNickName(), properties.getDonenoticetemplateid());
                log.info("发送通知消息内容:{}", noticeMsg);
                String sendUrl = properties.getTemplateurl() + token;
                String responseMsg = HttpClientProxy.post(sendUrl, noticeMsg);
                log.info("发送通知消息响应:{}", responseMsg);
                resp.getWriter().write("发送通知消息成功");
            } else {
                resp.getWriter().write("未能理解操作指示");
            }
        } catch (Exception e) {
            log.error("保存数据发生异常", e);
        }
    }
}
